<?php
/**
 * Book Chapter Category Model
 *
 * @author hiscaler <hiscaler@gmail.com>
 * @link http://www.yuandot.com/
 * @copyright Copyright &copy; 2009-2010 Yuandot Information Technology CO.,LTD.
 * @license http://doit.yuandot.com/license/
 */
class BookChapterCategory extends CActiveRecord {
    /**
     * The followings are the available columns in table '{{books_chapters_categories}}':
     * @var integer $id
     * @var integer $parent_id
     * @var integer $book_id
     * @var string $title
     * @var string $author
     * @var string $summary
     * @var string $summary_formatted
     * @var integer $status
     * @var integer $order_pos
     * @var integer $created
     * @var integer $updated
     */

    /**
     * Returns the static model of the specified AR class.
     * @return CActiveRecord the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{books_chapters_categories}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
        array('book_id, title, author, summary, summary_formatted', 'required'),
        array('parent_id, book_id, status, order_pos, created, updated', 'numerical', 'integerOnly'=>true),
        array('status', 'boolean', 'trueValue' => 1, 'falseValue' => 0),
        array('title, author', 'length', 'max'=>200),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            // 分类所属书籍
            'book' => array(self::BELONGS_TO, 'Book', 'book_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'Id',
            'parent_id' => Yii::t('bookChapterCategory', 'parent_id'),
            'book_id' => Yii::t('bookChapterCategory', 'book_id'),
            'title' => Yii::t('bookChapterCategory', 'title'),
            'author' => Yii::t('bookChapterCategory', 'author'),
            'summary' => Yii::t('bookChapterCategory', 'summary'),
            'status' => Yii::t('bookChapterCategory', 'status'),
            'order_pos' => Yii::t('common', 'order_pos'),
            'created' => Yii::t('common', 'created'),
            'updated' => Yii::t('common', 'updated'),
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'created',
                'updateAttribute' => 'updated',
            )
        );
    }

    const STATUS_HIDE = 0;
    const STATUS_SHOW = 1;
    public function getStatusOptions() {
        return array(
            self::STATUS_HIDE => Yii::t('bookChapterCategory', 'status_hide'),
            self::STATUS_SHOW => Yii::t('bookChapterCategory', 'status_show'),
        );
    }

    protected function beforeValidate() {
        parent::beforeValidate();
        $parser = new CMarkdownParser();
        $this->summary_formatted = $parser->safeTransform($this->summary);
        
        return true;
    }

    private $_ids;
    public function getIds($parent_id = 1, $include_self = true, $include_subs = true) {
        if ($include_self) $this->_ids[] = $parent_id;
        $criteria = new CDbCriteria();
        $criteria->condition = "parent_id = {$parent_id}";
        $criteria->select = array('id');
        $nodes = self::model()->findAll($criteria);
        foreach ($nodes as $node) {
            $node_id = $node->id;
            if ($include_subs) {
                if ($this->hasChild($node_id)) {
                    $this->_ids[] = $node_id;
                    $this->getIds($node_id);
                } else {
                    $this->_ids[] = $node_id;
                }
            } else {
                $this->_ids[] = $node_id;
            }
        }
        return (count($this->_ids) > 2)
            ? array_unique($this->_ids) : $this->_ids;
    }

    /**
     * 返回 CTreeView 所需数据
     * @param <integer> $book_id 对应的书籍编号
     * @param <integer> $parent_id 父节点值
     * @param string $url 生成的树形 URL 链接地址
     * @param string $node_name 节点参数名称，默认为 node，比如你可以修改为 category
     * @param string $root_is_link 父节点是否为链接形式
     * @return <string>
     */
    public function getCTreeViewDatas($book_id = 0, $parent_id = 0, $url = '',
        $node_name = 'category', $root_is_link = true, $expanded = false) {
        if (intval($book_id)) {
            $datas = $this->generateCTreeViewDatas($book_id, $parent_id, $url,
                $node_name, $root_is_link);
            return (count($datas) && $datas != null)
                ? CArrayExt::toTree($datas, 'id', 'parent', 'children', $refs)
                : $datas;
        } else {
            return array();
        }
    }

    /**
     * 遍历节点属于 $parent_id 的所有子节点，供 getCTreeViewDatas 生成返回
     * CTreeView 所需数据
     * @var array
     */
    private $_CTreeView_datas;
    public function generateCTreeViewDatas($book_id, $parent_id = 0, $url = '',
        $node_name = 'category', $root_is_link = true, $expanded = false) {
        $criteria = new CDbCriteria;
        $criteria->condition = "book_id = {$book_id} AND parent_id = {$parent_id}";
        $criteria->order = 'order_pos ASC';
        $categories = self::model()->findAll($criteria);
        $node_name = (trim($node_name) == '') ? 'view' : trim($node_name);
        foreach ($categories as $j => $category) {
            $category_id = $category->id;
            if ($this->hasChild($category_id)) {
                if ($root_is_link) {
                    $text = CHtml::link($category->title, array($url, $node_name => $category->id, 'bid' => $category->book_id));
                } else {
                    $text = "<span>$category->title</span>";
                }
                $this->_CTreeView_datas[$category_id] = array(
                    'id' => $category_id,
                    'text' => $text,
                    'order_pos' => $category->order_pos,
                    'expanded' => $expanded,
                    'classes' => 'important',
                    'parent' => $category->parent_id,
                );
                $this->generateCTreeViewDatas($book_id, $category_id, $url, $node_name, $root_is_link);
            } else {
                $text = (trim($url) == '')
                    ? CHtml::link($category->title, array("{$category->title}/index", $node_name => $category->id, 'bid' => $category->book_id))
                    : CHtml::link($category->title, array($url, $node_name => $category->id, 'bid' => $category->book_id));
                $this->_CTreeView_datas[$category_id] = array(
                    'id' => $category_id,
                    'text' => $text,
                    'order_pos' => $category->order_pos,
                    'expanded' => $expanded,
                    'classes' => 'important',
                    'parent' => $category->parent_id,
                );
            }
        }

        return $this->_CTreeView_datas;
    }

    /**
     * 判断是否有子节点
     * @param integer $category_id
     * @return boolean
     */
    public static function hasChild($category_id) {
        $criteria = new CDbCriteria;
        $criteria->condition = "parent_id = {$category_id}";
        return (self::model()->count($criteria)) ? true : false;
    }

    // 设置章节内容所属分类
    public function addChapterContent($book_chapter_content) {
        $book_chapter_content->category_id = $this->id;
        return $book_chapter_content->save();
    }
}